package com.pactera.asmp.server.restfullapi;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.pactera.asmp.server.common.constants.Constants;
import com.pactera.asmp.server.common.constants.ResultCode;
import com.pactera.asmp.server.common.logprint.utils.StringUtils;
import com.pactera.asmp.server.entity.ConstantInfoDTO;
import com.pactera.asmp.server.entity.ConstantInfoSearchDTO;
import com.pactera.asmp.server.entity.ResponseResult;
import com.pactera.asmp.server.pojo.ConstantInfo;
import com.pactera.asmp.server.pojo.ScriptInfo2;
import com.pactera.asmp.server.service.IConstantInfoHistoryService;
import com.pactera.asmp.server.service.IConstantInfoService;
import com.pactera.asmp.server.utils.PageDataResult;

@RestController
@RequestMapping("/api/v1")
public class RestfulConstantApi {

    private static final Logger logger = LoggerFactory.getLogger(RestfulConstantApi.class);

    @Autowired
    private IConstantInfoService constantInfoService;

    @Autowired
    private IConstantInfoHistoryService constantInfoHistoryService;

//    @RequiresPermissions({PermissionCode.TEST_CASE})
    @PostMapping(value = "/constant/list", produces = "application/json;charset=UTF-8")
    public ResponseResult getConstantList(@RequestBody ConstantInfoSearchDTO constantInfoSearchDTO) {
        logger.info("POST /api/v1/constant/list getConstantList" );
        ResponseResult responseResult = new ResponseResult(ResultCode.SUCCESS);
        PageDataResult pdr ;
        JSONObject jsonObject = new JSONObject();
        if (null == constantInfoSearchDTO.getPage() || constantInfoSearchDTO.getPage().intValue() == 0) {
            constantInfoSearchDTO.setPage(1);
        }
        if (null == constantInfoSearchDTO.getLimit() || constantInfoSearchDTO.getLimit().intValue() == 0) {
            constantInfoSearchDTO.setLimit(10);
        }

        if(constantInfoSearchDTO.getPage().intValue() < 0 || constantInfoSearchDTO.getLimit().intValue() < 0) {
            jsonObject.put("totals", 0);
            jsonObject.put("list", Lists.newArrayList());
            responseResult.setData(jsonObject);
            return responseResult;
        }
        pdr = constantInfoService.select(constantInfoSearchDTO);
        jsonObject.put("totals", pdr.getTotals());
        jsonObject.put("list", pdr.getList());
        responseResult.setData(jsonObject);
        return responseResult;
    }

    @PostMapping(value = "/constant",  produces = "application/json;charset=UTF-8")
    public ResponseResult addConstant(@RequestBody ConstantInfoDTO constantInfoDTO) {
        logger.info("POST /api/v1/constant addConstant");
        if (null == constantInfoDTO) {
            return new ResponseResult(ResultCode.PARAM_IS_BLANK);
        }
        if (StringUtils.isEmpty(constantInfoDTO.getName())
                || constantInfoDTO.getConstantData() == null
                || StringUtils.isEmpty(constantInfoDTO.getDuid())
                || constantInfoDTO.getProjectId() == null) {
            return new ResponseResult(ResultCode.PARAM_NOT_COMPLETE);
        }
        if (!constantInfoDTO.getName().matches(Constants.REGEXP_FIRST_LAST_NOT_SPACE)) {
            return new ResponseResult(ResultCode.PARAM_TYPE_BIND_ERROR);
        }
        ConstantInfoDTO infoDTO = constantInfoService.insert(constantInfoDTO);
        return ResponseResult.defaultSuccess(infoDTO.getId());
    }

    @PutMapping(value = "/constant",  produces = "application/json;charset=UTF-8")
    public ResponseResult updateConstant(@RequestBody ConstantInfo constantInfo) {
        logger.info("PUT /api/v1/constant");
        if (constantInfo == null
                || constantInfo.getId() == null
                || StringUtils.isEmpty(constantInfo.getName())
                || constantInfo.getConstantData() == null
                || StringUtils.isEmpty(constantInfo.getDuid())
                || constantInfo.getProjectId() == null) {
            return new ResponseResult(ResultCode.PARAM_IS_BLANK);
        }
        if (!constantInfo.getName().matches(Constants.REGEXP_FIRST_LAST_NOT_SPACE)) {
            return new ResponseResult(ResultCode.PARAM_TYPE_BIND_ERROR);
        }
        handleUpdateTime(constantInfo);
        return constantInfoService.update(constantInfo) ? new ResponseResult(ResultCode.SUCCESS) : new ResponseResult(ResultCode.SYSTEM_INNER_ERROR);
    }

    private void handleUpdateTime(ConstantInfo constantInfo) {
        Date date = new Date();
        Instant instant = date.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();
        LocalDateTime updateTime = instant.atZone(zoneId).toLocalDateTime();
        constantInfo.setUpdateTime(updateTime);
    }

    @DeleteMapping(value = "/constant", produces = "application/json;charset=UTF-8")
    public ResponseResult deleteConstant(@RequestBody List<Long> datas) {
        logger.info("delete /api/v1/constant deleteConstant ");
        if (datas.isEmpty()) {
            return new ResponseResult(ResultCode.PARAM_IS_BLANK);
        }
        return constantInfoService.delete(datas) ? new ResponseResult(ResultCode.SUCCESS) : new ResponseResult(ResultCode.SYSTEM_INNER_ERROR);
    }

    @GetMapping("/historyConstant/list")
    public ResponseResult getHistoryConstantList(Long constantId, Integer page, Integer limit) {
        ResponseResult responseResult = new ResponseResult(ResultCode.SUCCESS);
        logger.info("GET /api/v1/historyConstant/list getHistoryConstantList" );
        PageDataResult pdr = constantInfoHistoryService.selective(constantId, page, limit);
        responseResult.setData(pdr);
        return responseResult;
    }

    @GetMapping(value = "/constant/relScprit", produces = "application/json;charset=UTF-8")
    public ResponseResult getRelScpritList(Long constantId) {
        logger.info("GET /api/v1/constant/relScprit getRelScpritList" );
        ResponseResult responseResult = new ResponseResult(ResultCode.SUCCESS);
        List<ScriptInfo2> scriptInfoList = constantInfoService.selectRelScpritList(constantId);
        responseResult.setData(scriptInfoList);
        return responseResult;
    }

}
